﻿<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Mwbuser extends CI_Model{
   // public  $error_code = 0;
    function __construct() {
        //parent::__construct();
    }
    //设置表吗
    function settok($tok,$expires,$wb_id)
    {
        $neex = time() + $expires;
        $DB1 = $this->load->database('update', TRUE);
        $DB1->query("update wtt_customers set access_token='". $tok."',expires=". $neex ." where wb_id=" .$wb_id);
        if($this->db->affected_rows() > 0)
        {
            return TRUE;
        }else{
            return FALSE;
        }
    }
    function setwbuser($userdata){
        $wb_id = $userdata['uid'];
        $query = $this->db->query('select wb_id,screen_name,status,followers_count,gender,jifen,coins,access_token,upuserinfo,profile_image_url from wtt_customers where wb_id='.$wb_id . ' limit 1');
	 
        if ($query->num_rows() > 0){
		
             $row1 = $query->row_array();
             if($row1['access_token'] != $userdata['access_token']){
                 $this->settok($userdata['access_token'], $userdata['expires_in'], $wb_id);
                 $row1['access_token'] = $userdata['access_token'];
              }
			 
			  //更新粉丝名称时间
              if(time() > ($row1['upuserinfo']+86400))
              {
                  $this->upuserinfo($wb_id, $userdata['access_token']);
              }
              $this->settodate($wb_id, 0, 1);  
        }else{
          
          $this->sinaapi->access_token =$userdata['access_token'];
          $wb_info = $this->sinaapi->show_user_by_id($wb_id);
          	 
          if(is_array($wb_info) && !isset($wb_info['error']) ){
                $str_array = array(
                    'wb_id'=>$wb_id,
                    'screen_name'=>$wb_info['screen_name'],
                    'province'=>$wb_info['province'],
                    'city'=>$wb_info['city'],
                    'location'=>$wb_info['location'],
                    'gender'=>$wb_info['gender'],
                    'verified'=>$wb_info['verified'],
                    'verified_type'=>$wb_info['verified_type'],
                    'verified_reason'=>$wb_info['verified_reason'],
                    'followers_count'=>$wb_info['followers_count'],
                    'profile_image_url'=>$wb_info['profile_image_url'],
                    'avatar_large'=>$wb_info['avatar_large'],
                    'jifen'=>$this->data['siteset']['reg_give_points'],
                    'access_token'=>$userdata['access_token'],
                    'expires'=> time() + $userdata['expires_in'],
                    'upuserinfo'=>  time(),
                    'reg_time' => time()
                );
                $DB1 = $this->load->database('update', TRUE);
                $DB1->insert('wtt_customers',$str_array );
                $str_array = array(
                    'uid'=>$wb_id,
                    'updata'=>  time()
                );
                $DB1->insert('wtt_mytodate',$str_array );
                $row1 = array(
                    'wb_id' => $wb_id,
                    'screen_name' => $wb_info['screen_name'],
                    'status' => 0,
					'coins' => 0,
                    'jifen' => $this->data['siteset']['reg_give_points'],
                    'followers_count'=>$wb_info['followers_count'],
                    'gender'=>$wb_info['gender'],
                     'verified'=>$wb_info['verified'],
                    'verified_type'=>$wb_info['verified_type'],
                    'verified_reason'=>$wb_info['verified_reason'],
                    'profile_image_url'=>$wb_info['profile_image_url'],
                    'access_token' => $userdata['access_token']
                );
                
                if ($this->session->userdata('cinvite'))
                {
                    $upu = $this->getinfo($this->session->userdata('cinvite'), 'screen_name');
                    $isok = false;
                    if(!empty($upu)){
                        $this->db->select('update,num');
                        $this->db->from('wtt_chky');
                        $this->db->where('uid',$this->session->userdata('cinvite'));
                        $query = $this->db->get();
                        if($query->num_rows() >0){
                            $row = $query->row_array();
                            $uptime = $row['update'];
                            $num = $row['num'];
                            $screen_name = $row['screen_name'];
                            if(date('y-n-j',$uptime) != date('y-n-j',time())){
                                $isok = TRUE;
                                $newnum = 1;
                            }else{
                                if($num < $this->data['siteset']['invite_limits'])
                                {
                                  $isok = TRUE;
                                  $newnum = $num+1;
                                }
                            }
                            if($isok){
                                $data = array(
                                    'update'=>  time(),
                                    'num' => $newnum
                                );
                                $DB1->where('uid',$this->session->userdata('cinvite'));
                                $DB1->update('wtt_chky',$data);
                            }
                        }else{
                            $isok = TRUE;
                            $data = array(
                                'uid' =>$this->session->userdata('cinvite'),
                                'update' => time(),
                                'num'=>1
                            );
                            $DB1->insert('wtt_chky',$data);
                        }
                       if($isok){
                           $this->sys_give($this->session->userdata('cinvite'),$wb_id,$screen_name,5,$this->data['siteset']['invite_points'],$this->data['siteset']['invite_coins']);//系统给的                            	
                           $this->_insert_tuijian($wb_id,$this->session->userdata('cinvite'));
                       } 
                       
                    }
                    $this->session->set_userdata('cinvite','');
                }
                
                
        
          }else{
              return $row1['error'] =TRUE;
          }
          
        }
		 
        return  $row1;
        
    }
    
    function upuserinfo($uid,$access_token)
    {
        $this->sinaapi->access_token =$access_token;
        $DB1 = $this->load->database('update', TRUE);
        $wb_info = $this->sinaapi->show_user_by_id($uid);
         
        if(is_array($wb_info) && !isset($wb_info['error']) ){
            $str_array = array(
                   'screen_name'=>$wb_info['screen_name'],
                    'province'=>$wb_info['province'],
                    'city'=>$wb_info['city'],
                    'location'=>$wb_info['location'],
                    'gender'=>$wb_info['gender'],
                	'verified'=>$wb_info['verified'],
                    'verified_type'=>$wb_info['verified_type'],
                    'verified_reason'=>$wb_info['verified_reason'],
                    'followers_count'=>$wb_info['followers_count'],
                    'profile_image_url'=>$wb_info['profile_image_url'],
                    'avatar_large'=>$wb_info['avatar_large'],
                    'upuserinfo'=>  time()
                );
                $DB1->where('wb_id',$uid);
                $DB1->update('wtt_customers',$str_array);
            
        }
        
    }
function gettodaydorepostcount($uid){   
	
		$query = $this->db->get_where('wtt_chknum',array('uid'=>$uid),1);
       if($query->num_rows() >0)
       {
          $row = $query->row_array();
          $follownum = $row['follownum'];
          $rpostnum = $row['rpostnum'];
          $d_f_n = $row['d_f_n'];
          $d_r_n = $row['d_r_n'];
       }

      return $d_r_n;
    }
    function gettuiguang($uid)
    {
       $re_arr = array('allnum'=>0,'stopnum'=>0);
       $r_count = 0;
       $r_scount = 0;
       $query = $this->db->get_where('wtt_follow',array('uid'=>$uid));
       if($query->num_rows() > 0){
           $row = $query->row_array();
           $re_arr['allnum'] = 1;
           if($row['follow_status'] == '0') $re_arr['stopnum'] = 1;
       }
       $this->db->where('uid',$uid);
       //$this->db->where('uid',$uid);
       $this->db->from('wtt_repost');
       
       $r_count = $this->db->count_all_results();
       if($r_count > 0){
           $this->db->where('uid',$uid);
           $this->db->where('rp_status',0);
           $this->db->from('wtt_repost');
           $r_scount = $this->db->count_all_results();
       }
       $re_arr['stopnum'] =$re_arr['stopnum'] + $r_scount;
       $re_arr['allnum'] = $re_arr['allnum'] + $r_count;
       return $re_arr;
     }
     function gettodata($uid)
     {
       $tjifen = array('shouru'=>0,'zhichu'=>0);
       $query = $this->db->get_where('wtt_mytodate',array('uid'=>$uid));
       if($query->num_rows() > 0){
          $row = $query->row_array();
          $tjifen['shouru'] = $row['shoru'];
          $tjifen['zhichu'] = $row['zhichu'];
       }
       return $tjifen;
     }
     
     function getinfo($uid,$sel='*')
     {
         $this->db->select($sel);
         $this->db->from('wtt_customers');
         $this->db->where('wb_id',$uid);
         $query = $this->db->get();
         return $query->row_array();
     }
      function getinfo2($id,$sel='*')
     {
         $this->db->select($sel);
         $this->db->from('wtt_exchange');
         $this->db->where('id',$id);
         $query = $this->db->get();
         return $query->row_array();
     }
     function getinfobyscreen_name($screen_name,$sel='*')
     {
         $this->db->select($sel);
         $this->db->from('wtt_customers');
         $this->db->where('screen_name',$screen_name);
         $query = $this->db->get();
         return $query->row_array();
     }
    

     //TODO:设置粉币
     function setcoins($touid,$coins,$paytype=1)
     {
     	 if(empty($touid) || ($coins<0)) return false;
         $DB1 = $this->load->database('update', TRUE);         
         if($paytype == '1')
         {        	
         	$DB1->query('update wtt_customers set coins=coins+'.$coins.' where wb_id='.$touid);              
         }else{
          	$DB1->query('update wtt_customers set coins=coins-'.$coins.' where wb_id='.$touid);   
         }
         if($DB1->affected_rows() < 1) return false;
         return true;             
     }
     //TODO:设置积分
     function setpoints($touid,$points,$paytype=1)
     {
     	 if(empty($touid) || ($points<0)) return false;
         $DB1 = $this->load->database('update', TRUE);         
         if($paytype == '1')
         {        	
         	$DB1->query('update wtt_customers set jifen=jifen+'.$points.' where wb_id='.$touid);              
         }else{
          	$DB1->query('update wtt_customers set jifen=jifen-'.$points.' where wb_id='.$touid);   
         }
         if($DB1->affected_rows() < 1) return false;
         return true;             
     }
     /*
      * 更新今天积分
      */
     function settodate($uid,$jifen,$ptype){
         $DB1 = $this->load->database('update', TRUE);
         $this->db->select('updata,shoru,zhichu');
         $this->db->from('wtt_mytodate');
         $this->db->where('uid',$uid);
         $query = $this->db->get();
         if($query->num_rows() > 0)
         {
            $row = $query->row_array();
             $update = $row['updata'];
             $shoru = $row['shoru'];
             $zhichu = $row['zhichu'];
             if(date('y-n-j',$update) != date('y-n-j',time()))
             {
                $shoru = 0;
                $zhichu = 0;
                $ptype == '1' ? $shoru = $jifen : $zhichu = $jifen ;
                $data = array(
                'shoru' => $shoru,
                'zhichu' => $zhichu,
                'updata' =>time()
            );
                
             }else{
                $ptype == '1' ? $shoru = $shoru + $jifen : $zhichu = $zhichu + $jifen ;
                 $data = array(
                'shoru' => $shoru,
                'zhichu' => $zhichu,
                'updata' =>time() 
                );
             }
            $DB1->where('uid', $uid);
            $DB1->update('wtt_mytodate', $data);  
         }else{
            $shoru = 0;
            $zhichu = 0;
            $ptype == '1' ? $shoru = $jifen : $zhichu = $jifen ;
            $data = array(
                'uid'=>$uid,
                'shoru' => $shoru,
                'zhichu' => $zhichu,
                'updata' =>time()
            );
             $DB1->insert('wtt_mytodate',$data); 
         }
         
         
     }
     /*设置日志
      * $uid 当前用户id
      * $touid 被操作uid
      * $types 类型 //1，关注，2转发 ，3 充值,4,分享 ，5邀请好友,6违规，7，违规返还  8,签到 9，抽奖 10,兑换实物 ,11 转让积分
      * $paytype 1收入，2 支出   
      * $points 积分
      *$coints 金币
      */
     
     function insertlog($uid,$touid,$nickname,$types,$points=0,$coins=0,$paytype=1,$show=0)
     {
         $DB1 = $this->load->database('update', TRUE);
         if (!empty($uid)&& empty($nickname)) {
         	$ninfo=$this->getinfo($uid,'screen_name');
         	$nickname=$ninfo['screen_name'];         	
         }
        if(empty($touid) || $touid != '0')
        {
            $tuinfo = $this->getinfo($touid, 'screen_name');
            if(empty($tuinfo)){
                $tonickname = '';
            }else{
                $tonickname = $tuinfo['screen_name'];
            }            
        }
         if($types == '1' || $types == '2' ){
         
         $data = array(
             array(
                 'uid'=>$uid,
                 'touid'=>$touid,
                 'nickname'=>$nickname,
                 'types'=>$types,
                 'datatime'=> time(),
                 'paytype'=>1,
                 'points'=>$points,
                 'coins'=>$coins,
                 'tonickname'=>$tonickname
             ),
             array(
                 'uid'=>$touid,
                 'touid'=>$uid,
                 'nickname'=>$tonickname,
                 'tonickname'=>$nickname,
                 'types'=>$types,
                 'datatime'=>  time(),
                 'paytype'=>2,
                 'points'=>$points,
                  'coins'=>$coins,
             ),
         );
         $DB1->insert_batch('wtt_pays',$data);
        }else{
           $data = array(
                 'uid'=>$uid,
                 'touid'=>$touid,
                 'nickname'=>$nickname,
                 'types'=>$types,
                 'datatime'=> time(),
                 'paytype'=>$paytype,
                 'points'=>$points,
                  'coins'=>$coins,
                 'tonickname'=>$tonickname,
                 'showtype'=>$show
             );
             $DB1->insert('wtt_pays',$data);
        }
        $newtime = (time()-120*3600);
        $DB1->where('datatime <',$newtime);
        $DB1->delete('wtt_pays'); 
         return true;
     }
	
     //TODO:系统设置赠送
	function sys_give($uid,$touid,$nickname,$type,$points=0,$coins=0){
		  $paytype=1;

		$this->setpoints($uid,$points,$paytype);
		$this->setcoins($uid,$coins,$paytype);  
		$this->insertlog($uid, $touid, $nickname, $type,$points,$coins,$paytype);		
	}
     
    function getlogs($uid,$p,$ptype,$pagesizes=10)
    {
        if(empty($uid)) return '登录超时，请重新登录';
        if(!is_numeric($p)) return '参数错误！1';
        if(!is_numeric($ptype)) return '参数错误！2';
        $this->db->select('touid,tonickname,types,datatime,points,coins,paytype,showtype');
        $this->db->from('wtt_pays');
        $this->db->where('uid',$uid);
        if($ptype == '0')
        {
            $this->db->where('paytype',1);  
        }else{
            $this->db->where('paytype',2); 
        }
        $this->db->order_by('datatime','desc');
        $num = ($p-1)*$pagesizes;
        $this->db->limit($pagesizes,$num);
        $query = $this->db->get();
        return $query->result_array();
    }
    function getlogpage($uid,$ptype)
    {
        $this->db->where('uid',$uid);
        if($ptype == '0')
        {
            $this->db->where('paytype',1);  
        }else{
            $this->db->where('paytype',2); 
        }
        return $this->db->count_all_results('wtt_pays');
    }
    
    function insetchkpay($uid,$touid,$status_id,$mid,$ptype,$points)
    {
	    $DB1 = $this->load->database('update', TRUE);
        $data = array(
            'uid'=> $uid,
            'touid' => $touid,
            'status_id' => $status_id,
            'ptype' => $ptype,
            'mid' => $mid,
            'points'=>$points,
            'datatime' => time()
        );
        $DB1->insert('wtt_chkpay',$data);
    }
    
    function chkpay($uid,$touid,$status_id,$ptype){
        if($ptype == '1')
        {
            
            $this->db->where('uid',$uid);
            $this->db->where('touid',$touid);
            
        }else{
            $this->db->where('uid',$uid);
            $this->db->where('status_id',$status_id);
        }
        return $this->db->count_all_results('wtt_chkpay');
    }
    
    
    	
     //TODO:邀请分享
    function dopost($uid,$content,$action){
        if(empty($uid)) return '登录超时，请重新登录';
        if(empty($content)) return '邀请内容不能为空！';
        $uinfo = $this->getinfo($uid['wb_id'], 'rptime');
        if(empty($uinfo)) return '获取用户信息错误！';
        $retime = $uinfo['rptime'];
        if($action =='inviteshare'){
        	if(time() < ($retime+6*3600))   return '邀请间隔不可小于6个小时';
        } 
        
        $rpinfo = $this->sinaapi->fenxiang($content);
		file_put_contents("D://log1.txt",json_encode($rpinfo));
        if(isset($rpinfo['error']) || !empty($rpinfo['error'])){
              $this->config->load('apierror', TRUE);
            $errinfo = $this->config->item($rpinfo['error_code'], 'apierror');
                if(!$errinfo) $errinfo = '未知错误';                 
            return $errinfo; 
        }else{                       
            $DB1 = $this->load->database('update', TRUE);
            $DB1->where('wb_id', $uid['wb_id']);
            $DB1->update('wtt_customers',array('rptime'=>  time()));                    
            return '';
        }
                
                
    }
    
    //检查写入推荐积分
    function tuijians($uid,$invite_points,$coins)
    {
        $query = $this->db->query('select * from wtt_tuijian where uid=\''.$uid.'\'');
        if($query->num_rows() > 0 ){
            $row = $query->row_array();
            $upu = $this->getinfo($row['touid'], 'screen_name');
            if(!empty($upu)){
                $this->setpoints($row['touid'], $invite_points, 1);
                 $this->setcoins($uid['wb_id'],$invite_coins,1); //完成邀请分享
                 //        insertlog($uid,$touid,$nickname,$types,$points,$coins,$paytype=1,$show=0)
                $this->insertlog($row['touid'], $uid, $upu['screen_name'], 5, $invite_points,$invite_coins);
                //更新积分后删除记录
                $DB1 = $this->load->database('update', TRUE);
                $DB1->delete('wtt_tuijian',array('uid'=>$uid));
            }
            
        }
    }
    
  
    
    private function _insert_tuijian($uid,$touid)
    {
        $data = array(
            'uid'=>$uid,
            'touid'=>$touid,
            'datatime' =>time()
        );
        $DB1 = $this->load->database('update', TRUE);
        $DB1->insert('wtt_tuijian',$data);
        return true;
    }
}

